CK Editor

  • STEP 1 : Packages
    
                                   <script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
    
                                  <script type = "text/javascript" src = "tinymce/tinymce.min.js"></script>
    
    
                                  <script type = "text/javascript" src = "tinymce/jquery.tinymce.min.js"></script>
    
                                  <script type = "text/javascript" src = "tinymce/main.js"></script>
                          
  • STEP 2 : Usage
    
                              <textarea id="mytextarea" name="content">Hello, World!</textarea>
                          

    1. The font size toolbar menu

    
                          tinymce.init({
                            /* ... */
                            toolbar:
                              "undo redo | styleselect | fontsizeselect | bold italic | alignleft aligncenter alignright alignjustify | outdent indent",
                          });
    
    
                          

    2. Define your available font sizes

    
                          tinymce.init({
                            /* ... */
                            fontsize_formats:
                              "8pt 9pt 10pt 11pt 12pt 14pt 18pt 24pt 30pt 36pt 48pt 60pt 72pt 96pt",
                          });
    
    
                          
    
                          tinymce.init({
                              selector: 'textarea',
                              toolbar: "undo redo | styleselect | fontsizeselect | bold italic | alignleft aligncenter alignright alignjustify | outdent indent",
                              fontsize_formats: "8pt 9pt 10pt 11pt 12pt 14pt 18pt 24pt 30pt 36pt 48pt 60pt 72pt 96pt",
                              content_style: "body { font-size: 14pt; }",
                              height: 350
                            });
    
                            

    3. Add the font as a menu option

    
                            tinymce.init({
                                /* ... */
                                font_formats:
                                  "Andale Mono=andale mono,times; Arial=arial,helvetica,sans-serif; Arial Black=arial black,avant garde; Book Antiqua=book antiqua,palatino; Comic Sans MS=comic sans ms,sans-serif; Courier New=courier new,courier; Georgia=georgia,palatino; Helvetica=helvetica; Impact=impact,chicago; Symbol=symbol; Tahoma=tahoma,arial,helvetica,sans-serif; Terminal=terminal,monaco; Times New Roman=times new roman,times; Trebuchet MS=trebuchet ms,geneva; Verdana=verdana,geneva; Webdings=webdings; Wingdings=wingdings,zapf dingbats",
                              });
    
    
                              

    block_formats

    
                              tinymce.init({
                                selector: 'textarea',  // change this value according to your HTML
                                block_formats: 'Paragraph=p; Header 1=h1; Header 2=h2; Header 3=h3'
                              });
                            

    font_family_formats

    
                            tinymce.init({
                              selector: 'textarea',  // change this value according to your HTML
                              toolbar: 'fontfamily',
                              font_family_formats: 'Arial=arial,helvetica,sans-serif; Courier New=courier new,courier,monospace; AkrutiKndPadmini=Akpdmi-n'
                            });
    
                            

    Using color_map

    
                            tinymce.init({
                              selector: 'textarea',  // change this value according to your HTML
                              toolbar: 'forecolor backcolor',
                              color_map: [
                                '000000', 'Black',
                                '808080', 'Gray',
                                'FFFFFF', 'White',
                                'FF0000', 'Red',
                                'FFFF00', 'Yellow',
                                '008000', 'Green',
                                '0000FF', 'Blue'
                              ]
                            });
    
                            

    content_langs

    
                            tinymce.init({
                              selector: 'textarea', // change this according to your HTML
                              toolbar: 'language',
                              content_langs: [
                                { title: 'English', code: 'en' },
                                { title: 'Spanish', code: 'es' },
                                { title: 'French', code: 'fr' },
                                { title: 'German', code: 'de' },
                                { title: 'Portuguese', code: 'pt' },
                                { title: 'Chinese', code: 'zh' }
                              ]
                            });
    
                            

    images_file_types

    
                            tinymce.init({
                              selector: 'textarea',  // change this value according to your HTML
                              plugins: 'image',
                              toolbar: 'image',
                              images_file_types: 'jpg,svg,webp'
                            });
    
                            

    file_picker_types

    
                            tinymce.init({
                              selector: 'textarea',  // change this value according to your HTML
                              file_picker_types: 'file image media'
                            });
                            

    browser_spellcheck

    
                            tinymce.init({
                              selector: 'textarea',  // change this value according to your HTML
                              browser_spellcheck: true
                            });
                            
  • STEP 3 : PHP : save image
    
                                  
                          public function makeurl($str)
                        {
    
    
                            $clean = preg_replace("/[^a-zA-Z0-9 -]/", "", $str);
                            $clean = strtolower($clean);
                            $clean = str_replace(" ", "-", $clean);
                            return $clean;
                        }
    
                        public function convertimage($pagecontent,$url='page')
                        {
                            $arraydata = explode('"', $pagecontent);       
    
                            $count=0;
                            foreach ($arraydata as $imagedata) {
                              
                                if (substr($imagedata, 0, 10) == "data:image") {
                                    $image_info = getimagesize($imagedata);
                                    $image_parts = explode(";base64,", $imagedata);
    
                                    
                                    
                                    //print_r($image_info);exit;
    
    
                                        if ($arraydata[$count + 2] == "") {
                                            $arraydata[$count + 2]=$url;
                                        }
                                      
                                        $url='public/uploads/content';
                                        $urls='public/uploads/content/';
                                        if (!file_exists('public/uploads/content/')) {
                                            mkdir('public/uploads/content/');
    
                                        }
                                  
                                      
                                        $urlcount=0;
                                        if($image_info['mime']=='image/jpeg'){
                                                    $url = $urls . $this->makeurl($arraydata[$count + 2]) . '.jpg';
    
                                                    while (file_exists($url)) {
                                                        $url = $urls . $this->makeurl($arraydata[$count + 2])."-".$urlcount . '.jpg';
                                                        $urlcount++;
                                
                                                    }
    
    
                                                    try {
                                                
                                                        $data = base64_decode(substr($imagedata, 23, -1));
                                                        $formImage = imagecreatefromstring($data);
                                
                                                        imagejpeg($formImage, $url, 100);
                                                        $arraydata[$count] =  $url;
                                
                                                            
                                
                                                    } catch (ErrorException $ex) {
                                                        
                                
                                                    }
    
    
                                        }
    
                                        if($image_info['mime']=='image/png'){
                                                        $urlpng = $urls . $this->makeurl($arraydata[$count + 2]) . '.png';
    
                                                        while (file_exists($urlpng)) {
                                                            $urlpng = $urls . $this->makeurl($arraydata[$count + 2])."-".$urlcount . '.png';
                                                            $urlcount++;
                                    
                                                        }
    
    
                                                        try {
                                                    
                                                                                    
                                    
                                                            $image_base64 = base64_decode($image_parts[1]);
                                                            file_put_contents($urlpng, $image_base64);
                                                            $arraydata[$count] =  $urlpng;
                                    
                                    
                                                        } catch (ErrorException $ex) {
                                                            
                                    
                                                        }
    
    
                                        }                    
                                      
                                        
    
    
    
                                }
                                $count++;
                            }
                            $arraydata = implode('"', $arraydata);
                            return $arraydata;
    
                        } 
    
    
    
    
                         
                          

    Usage

    in controller function

    
                          $input['content']=$this->convertimage($input['content'], $input['title']);
    
                          $search = ["../", "../../", "../../../", "../../../../"];
                          $input['content']=str_replace($search, '',$input['content']);
    
                          

    in html

    
                          <textarea id="mytextarea" class="" name="content" ><?php echo str_replace("public/uploads/content","../../public/uploads/content",$content['content'])?></textarea>
                          
  • STEP 4 : Htaccess
    
                  RewriteEngine On
    
    
                  RewriteRule ^.*/uploads/(.*)/(.*)$ /jaivamlife/london_road_laravel/public/uploads/$1/$2 [L,R=301]
    
    
                  RewriteCond %{HTTP:Authorization} ^(.*)
                  RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]
    
    
    
                  RewriteCond %{REQUEST_FILENAME} !-d
    
                  RewriteRule ^(.*)/$ /$1 [L,R=301]
                  
                    
                  
                  RewriteCond %{REQUEST_URI} !(\.css|\.js|\.png|\.jpg|\.gif|robots\.txt)$ [NC]
                  RewriteCond %{REQUEST_FILENAME} !-d
                  RewriteCond %{REQUEST_FILENAME} !-f
                  RewriteRule ^ index.php [L]    
                    
                  RewriteCond %{REQUEST_FILENAME} !-d
                  RewriteCond %{REQUEST_FILENAME} !-f
                  RewriteCond %{REQUEST_URI} !^/public/
                  RewriteRule ^(css|js|images)/(.*)$ public/$1/$2 [L,NC]
    
    
    
                      
    Note: RewriteRule ^.*/uploads/(.*)/(.*)$ /jaivamlife/london_road_laravel/public/uploads/$1/$2 [L,R=301]
  • STEP 5 : Image uploading using ajax

    1. in html

    
                  <textarea class="form-control" rows="5" id="tiny-description" name="description"></textarea>
                  

    2. in editor script

    
    
    
                  tinymce.init({
        selector: 'textarea#tiny-description',
        width:'100%',
        height: 250,
         plugins: [
            "code ",
            "paste"
        ],
        toolbar: "undo redo | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link code image_upload",
        menubar:false,
        statusbar: false,
        content_style: ".mce-content-body {font-size:15px;font-family:Arial,sans-serif;}",
        setup: function(editor) {
            var fileInput = $('<input id="tinymce-uploader" type="file" name="pic" accept="image/*" style="display:none">');
            jQuery(editor.getElement()).parent().append(fileInput);
            fileInput.on("change",function(){           
                var filename = this.files[0];
                var reader = new FileReader();          
                var formData = new FormData();
                var files = filename;
                formData.append("file",files);
                formData.append('filetype', 'image');               
                jQuery.ajax({
                    url: "upload.php",
                    type: "post",
                    data: formData,
                    contentType: false,
                    processData: false,
                    async: false,
                    dataType: 'json',
                    success: function(json){
                        var fileName = json.file_path;
                        if(fileName) {
                            editor.insertContent('<img src="'+fileName+'"/>');
                        }
                    }
                });             
                reader.readAsDataURL(filename);  
            });    
    
            // add Button
            editor.ui.registry.addButton('image_upload', {
              icon: 'image',
              onAction: () => {
                    fileInput.trigger('click');
                }
            });
            
        }
    });
    
    
    

    3. in upload.php

    
    
    // Allowed the origins to upload 
    $accepted_origins = array("http://localhost", "https://webhaunt.com/");
    // Images upload dir path
    $uploadFolder = "assets/upload/";
    reset($_FILES);
    $tmp = current($_FILES);
    if(is_uploaded_file($tmp['tmp_name'])){
        if(isset($_SERVER['HTTP_ORIGIN'])){
            if(in_array($_SERVER['HTTP_ORIGIN'], $accepted_origins)){
                header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']);
            }else{
                header("HTTP/1.1 403 Origin Denied");
                return;
            }
        }
        // check valid file name
        if(preg_match("/([^\w\s\d\-_~,;:\[\]\(\).])|([\.]{2,})/", $tmp['name'])){
            header("HTTP/1.1 400 Invalid file name!");
            return;
        }
    
        // check and Verify extension
        if(!in_array(strtolower(pathinfo($tmp['name'], PATHINFO_EXTENSION)), array("gif", "jpg", "png", "bmp"))){
            header("HTTP/1.1 400 Invalid file extension!");
            return;
        }
      
        // Accept upload if there was no origin, or if it is an accepted origin
        $filePath = $uploadFolder . $tmp['name'];
        move_uploaded_file($tmp['tmp_name'], $filePath);
        // return successful JSON.
        echo json_encode(array('file_path' => $filePath));
    } else {
        header("HTTP/1.1 500 Server Error!");
    }